package com.g3d.core;

import java.util.ArrayList;

import android.media.AudioManager;
import android.media.SoundPool;

import com.g3d.objects.G3DSound;

public class G3DSoundManager 
{
	private static final int MAX_STREAMS_DEFAULT = 5;
	
	private float _masterVolume = 1.0f;

	private Object _lock = new Object();
	private ArrayList<G3DSound> _sounds = new ArrayList<G3DSound>();
	
	private SoundPool _soundPool;

	public G3DSoundManager()
	{
		this(MAX_STREAMS_DEFAULT);
	}

	public G3DSoundManager(int maxSimultaniusStreams)
	{
		this._soundPool = new SoundPool(maxSimultaniusStreams, AudioManager.STREAM_MUSIC, 0);
	}

	public SoundPool getSoundPool()
	{
		return this._soundPool;
	}
	
	public float masterVolume()
	{
		return this._masterVolume;
	}
	
	public void masterVolume(float volume)
	{
		this._masterVolume = volume;
		synchronized (this._lock) 
		{
			for (G3DSound sound: this._sounds) 
			{
				sound.updateVolume();
			}
		}
	}
	
	public void addSound(G3DSound sound)
	{
		synchronized (this._lock) 
		{
			this._sounds.add(sound);
		}
	}
	
	public void removeSound(G3DSound sound)
	{
		this._soundPool.stop(sound.getSoundId());
		this._soundPool.unload(sound.getSoundId());

		synchronized (this._lock) 
		{
			this._sounds.remove(sound);
		}
	}
	
	public void destroy()
	{
		this._soundPool.release();
		synchronized (this._lock) 
		{
			this._sounds.clear();
		}
	}
	
}
